package com.evaluation.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.evaluation.common.Result;
import com.evaluation.entity.DeptEvaluatingRelation;
import com.evaluation.entity.TeacherEvaluatingRelation;
import com.evaluation.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * PC端管理后台控制器
 */
@RestController
@RequestMapping("/api/admin")
public class AdminController {

    @Autowired
    private DeptEvaluatingRelationService deptEvaluatingRelationService;

    @Autowired
    private TeacherEvaluatingRelationService teacherEvaluatingRelationService;

    @Autowired
    private DeptService deptService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private IndicatorsService indicatorsService;

    @Autowired
    private IndicatorsPointsService indicatorsPointsService;

    @Autowired
    private PositionTypeService positionTypeService;

    @Autowired
    private DeptScoreService deptScoreService;

    @Autowired
    private TeacherScoreService teacherScoreService;

    @Autowired
    private DeptIndicatorsScoreService deptIndicatorsScoreService;

    @Autowired
    private TeacherIndicatorsScoreService teacherIndicatorsScoreService;

    @Autowired
    private IndicatorsWfService indicatorsWfService;

    /**
     * 获取统计数据
     */
    @GetMapping("/statistics")
    public Result<Map<String, Object>> getStatistics() {
        try {
            // 获取基础数据统计
            long totalDepts = deptService.lambdaQuery().eq(com.evaluation.entity.Dept::getBmzt, "0").count();
            long totalTeachers = teacherService.lambdaQuery().eq(com.evaluation.entity.Teacher::getJszt, "0").count();
            long totalIndicators = indicatorsService.count();
            long totalPositions = positionTypeService.lambdaQuery().eq(com.evaluation.entity.PositionType::getGwzt, "0").count();

            // 获取部门测评统计
            long totalDeptEvaluations = deptEvaluatingRelationService.count();
            long completedDeptEvaluations = deptEvaluatingRelationService.lambdaQuery()
                    .eq(com.evaluation.entity.DeptEvaluatingRelation::getCpbs, "1")
                    .count();

            // 获取教师测评统计
            long totalTeacherEvaluations = teacherEvaluatingRelationService.count();
            long completedTeacherEvaluations = teacherEvaluatingRelationService.lambdaQuery()
                    .eq(com.evaluation.entity.TeacherEvaluatingRelation::getCpbs, "1")
                    .count();

            // 计算完成率
            double deptProgress = totalDeptEvaluations > 0 ?
                    (double) completedDeptEvaluations / totalDeptEvaluations * 100 : 0;
            double teacherProgress = totalTeacherEvaluations > 0 ?
                    (double) completedTeacherEvaluations / totalTeacherEvaluations * 100 : 0;

            // 获取分数统计
            long deptScoreCount = deptScoreService.count();
            long teacherScoreCount = teacherScoreService.count();

            // 获取部门类型统计
            Map<String, Object> deptTypeStats = new HashMap<>();
            List<com.evaluation.entity.Dept> allDepts = deptService.lambdaQuery().eq(com.evaluation.entity.Dept::getBmzt, "0").list();
            long functionalDepts = allDepts.stream().filter(dept -> "0".equals(dept.getBmlx())).count(); // 职能部门
            long colleges = allDepts.stream().filter(dept -> "1".equals(dept.getBmlx())).count(); // 二级学院
            long communities = allDepts.stream().filter(dept -> "2".equals(dept.getBmlx())).count(); // 社区
            long others = allDepts.stream().filter(dept -> "3".equals(dept.getBmlx())).count(); // 其他

            deptTypeStats.put("functional", functionalDepts);
            deptTypeStats.put("college", colleges);
            deptTypeStats.put("community", communities);
            deptTypeStats.put("other", others);

            // 获取权限类型统计
            Map<String, Object> userTypeStats = new HashMap<>();
            List<com.evaluation.entity.Teacher> allTeachers = teacherService.lambdaQuery().eq(com.evaluation.entity.Teacher::getJszt, "0").list();
            long adminUsers = allTeachers.stream().filter(teacher -> "0".equals(teacher.getQxlx())).count(); // 管理员
            long schoolLeaders = allTeachers.stream().filter(teacher -> "1".equals(teacher.getQxlx())).count(); // 校领导
            long normalUsers = allTeachers.stream().filter(teacher -> teacher.getQxlx() == null || "".equals(teacher.getQxlx())).count(); // 普通用户

            userTypeStats.put("admin", adminUsers);
            userTypeStats.put("schoolLeader", schoolLeaders);
            userTypeStats.put("normal", normalUsers);

            Map<String, Object> statistics = new HashMap<>();
            statistics.put("totalDepts", totalDepts);
            statistics.put("totalTeachers", totalTeachers);
            statistics.put("totalIndicators", totalIndicators);
            statistics.put("totalPositions", totalPositions);

            statistics.put("totalDeptEvaluations", totalDeptEvaluations);
            statistics.put("completedDeptEvaluations", completedDeptEvaluations);
            statistics.put("deptProgress", Math.round(deptProgress * 10) / 10.0);

            statistics.put("totalTeacherEvaluations", totalTeacherEvaluations);
            statistics.put("completedTeacherEvaluations", completedTeacherEvaluations);
            statistics.put("teacherProgress", Math.round(teacherProgress * 10) / 10.0);

            statistics.put("deptScoreCount", deptScoreCount);
            statistics.put("teacherScoreCount", teacherScoreCount);
            statistics.put("deptTypeStats", deptTypeStats);
            statistics.put("userTypeStats", userTypeStats);

            return Result.success(statistics);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取统计数据失败");
        }
    }

    /**
     * 数据导出接口
     */
    @GetMapping("/export/{dataType}")
    public void exportData(@PathVariable String dataType, HttpServletResponse response) {
        try {
            // 注意：不要在这里设置响应头，让ExcelUtil.exportExcel方法来处理
            // 因为ExcelUtil会设置正确的XLSX格式响应头

            switch (dataType) {
                case "dept-info":
                    exportDeptInfo(response);
                    break;
                case "teacher-info":
                    exportTeacherInfo(response);
                    break;
                case "dept-relations":
                    exportDeptRelations(response);
                    break;
                case "teacher-relations":
                    exportTeacherRelations(response);
                    break;
                case "dept-scores":
                    exportDeptScores(response);
                    break;
                case "teacher-scores":
                    exportTeacherScores(response);
                    break;
                case "indicators":
                    exportIndicators(response);
                    break;
                case "indicator-points":
                    exportIndicatorPoints(response);
                    break;
                case "positions":
                    exportPositions(response);
                    break;
                case "summary-report":
                    exportSummaryReport(response);
                    break;
                case "detail-report":
                    exportDetailReport(response);
                    break;
                case "statistics-report":
                    exportStatisticsReport(response);
                    break;
                case "dept-indicator-scores":
                    exportDeptIndicatorScores(response);
                    break;
                case "dept-total-scores":
                    exportDeptTotalScores(response);
                    break;
                case "teacher-indicator-scores":
                    exportTeacherIndicatorScores(response);
                    break;
                case "teacher-total-scores":
                    exportTeacherTotalScores(response);
                    break;
                default:
                    response.getWriter().write("不支持的导出类型");
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.getWriter().write("导出失败：" + e.getMessage());
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * 获取部门测评列表
     */
    @GetMapping("/dept-evaluations")
    public Result<Page<DeptEvaluatingRelation>> getDeptEvaluations(@RequestParam(defaultValue = "1") Integer page,
                                     @RequestParam(defaultValue = "10") Integer size,
                                     @RequestParam(required = false) String bcpbm,
                                     @RequestParam(required = false) String cpjs,
                                     @RequestParam(required = false) String cpbs) {
        try {
            com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.evaluation.entity.DeptEvaluatingRelation> pageObj =
                    new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page, size);

            com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.evaluation.entity.DeptEvaluatingRelation> queryWrapper =
                    new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();

            if (bcpbm != null && !bcpbm.trim().isEmpty()) {
                queryWrapper.like("BCPBM", bcpbm);
            }
            if (cpjs != null && !cpjs.trim().isEmpty()) {
                queryWrapper.like("CPJS", cpjs);
            }
            if (cpbs != null && !cpbs.trim().isEmpty()) {
                queryWrapper.eq("CPBS", cpbs);
            }

            queryWrapper.orderByDesc("CPSJ");

            com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.evaluation.entity.DeptEvaluatingRelation> result =
                    deptEvaluatingRelationService.page(pageObj, queryWrapper);

            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取部门测评列表失败");
        }
    }

    /**
     * 获取教师测评列表
     */
    @GetMapping("/teacher-evaluations")
    public Result<Page<TeacherEvaluatingRelation>> getTeacherEvaluations(@RequestParam(defaultValue = "1") Integer page,
                                        @RequestParam(defaultValue = "10") Integer size,
                                        @RequestParam(required = false) String bcpjs,
                                        @RequestParam(required = false) String cpjs,
                                        @RequestParam(required = false) String cpbs) {
        try {
            com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.evaluation.entity.TeacherEvaluatingRelation> pageObj =
                    new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page, size);

            com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.evaluation.entity.TeacherEvaluatingRelation> queryWrapper =
                    new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();

            if (bcpjs != null && !bcpjs.trim().isEmpty()) {
                queryWrapper.like("BCPJS", bcpjs);
            }
            if (cpjs != null && !cpjs.trim().isEmpty()) {
                queryWrapper.like("CPJS", cpjs);
            }
            if (cpbs != null && !cpbs.trim().isEmpty()) {
                queryWrapper.eq("CPBS", cpbs);
            }

            queryWrapper.orderByDesc("CPSJ");

            com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.evaluation.entity.TeacherEvaluatingRelation> result =
                    teacherEvaluatingRelationService.page(pageObj, queryWrapper);

            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取教师测评列表失败");
        }
    }

    /**
     * 获取系统健康状态
     */
    @GetMapping("/health")
    public Result<Map<String, Object>> getSystemHealth() {
        try {
            Map<String, Object> health = new HashMap<>();

            // 检查数据库连接
            try {
                deptService.count();
                health.put("database", "正常");
            } catch (Exception e) {
                health.put("database", "异常：" + e.getMessage());
            }

            // 检查各个服务状态
            health.put("deptService", deptService != null ? "正常" : "异常");
            health.put("teacherService", teacherService != null ? "正常" : "异常");
            health.put("evaluationService", deptEvaluatingRelationService != null ? "正常" : "异常");

            health.put("timestamp", System.currentTimeMillis());
            health.put("status", "运行中");

            return Result.success(health);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取系统健康状态失败");
        }
    }

    // ========== 私有方法：导出功能实现 ==========


    private void exportDeptInfo(HttpServletResponse response) throws Exception {
        try {
            List<com.evaluation.entity.Dept> deptList = deptService.lambdaQuery()
                    .eq(com.evaluation.entity.Dept::getBmzt, "0")
                    .orderByAsc(com.evaluation.entity.Dept::getBmbh)
                    .list();

            String[] headers = {"部门编号", "部门名称", "部门类型", "部门负责人", "联系电话", "状态"};
            String[] fields = {"bmbh", "bmmc", "bmlx", "bmfzr", "lxdh", "bmzt"};
            String fileName = "部门信息_" + System.currentTimeMillis() + ".xlsx";

            com.evaluation.util.ExcelUtil.writeExcel(response, deptList, headers, fields, fileName);
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("导出部门信息失败：" + e.getMessage());
        }
    }

    private void exportTeacherInfo(HttpServletResponse response) throws Exception {
        try {
            List<com.evaluation.entity.Teacher> teacherList = teacherService.lambdaQuery()
                    .eq(com.evaluation.entity.Teacher::getJszt, "0")
                    .orderByAsc(com.evaluation.entity.Teacher::getJsbh)
                    .list();

            String[] headers = {"教师编号", "教师姓名", "教师工号", "部门编号", "部门名称", "教师类型", "手机号码", "权限类型", "状态"};
            String[] fields = {"jsbh", "jsxm", "jsgh", "bmbh", "bmmc", "jslx", "sjhm", "qxlx", "jszt"};
            String fileName = "教师信息_" + System.currentTimeMillis() + ".xlsx";

            com.evaluation.util.ExcelUtil.writeExcel(response, teacherList, headers, fields, fileName);
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("导出教师信息失败：" + e.getMessage());
        }
    }

    private void exportDeptRelations(HttpServletResponse response) throws Exception {
        try {
            List<com.evaluation.entity.DeptEvaluatingRelation> relationList = deptEvaluatingRelationService.list();

            String[] headers = {"测评编号", "被测评部门", "测评教师", "测评指标", "测评状态", "总分", "测评时间"};
            String[] fields = {"cpbh", "bcpbm", "cpjs", "cpzbbh", "cpbs", "totalscore", "cpsj"};
            String fileName = "部门测评关系_" + System.currentTimeMillis() + ".xlsx";

            com.evaluation.util.ExcelUtil.writeExcel(response, relationList, headers, fields, fileName);
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("导出部门测评关系失败：" + e.getMessage());
        }
    }

    private void exportTeacherRelations(HttpServletResponse response) throws Exception {
        try {
            List<TeacherEvaluatingRelation> relationList = teacherEvaluatingRelationService.list();

            String[] headers = {"测评编号", "被测评教师", "测评教师", "测评指标", "测评状态", "总分", "测评时间"};
            String[] fields = {"cpbh", "bcpjs", "cpjs", "cpzbbh", "cpbs", "totalscore", "cpsj"};
            String fileName = "教师测评关系_" + System.currentTimeMillis() + ".xlsx";

            com.evaluation.util.ExcelUtil.writeExcel(response, relationList, headers, fields, fileName);
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("导出教师测评关系失败：" + e.getMessage());
        }
    }

    private void exportDeptScores(HttpServletResponse response) throws Exception {
        try {
            // 查询部门分数统计数据
            List<Map<String, Object>> scoreData = new ArrayList<>();
            List<com.evaluation.entity.DeptEvaluatingRelation> relations = deptEvaluatingRelationService.lambdaQuery()
                    .eq(com.evaluation.entity.DeptEvaluatingRelation::getCpbs, "1")
                    .orderByDesc(com.evaluation.entity.DeptEvaluatingRelation::getTotalscore)
                    .list();

            for (com.evaluation.entity.DeptEvaluatingRelation relation : relations) {
                Map<String, Object> item = new HashMap<>();
                item.put("被测评部门", relation.getBcpbm());
                item.put("测评教师", relation.getCpjs());
                item.put("总分", relation.getTotalscore());
                item.put("第一分数", relation.getFirstscore());
                item.put("第二分数", relation.getTwoscore());
                item.put("第三分数", relation.getThreescore());
                item.put("第四分数", relation.getFourscore());
                item.put("测评时间", relation.getCpsj());
                scoreData.add(item);
            }

            String fileName = "部门分数统计_" + System.currentTimeMillis();
            com.evaluation.util.ExcelUtil.exportExcel(response, fileName, scoreData);
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("导出部门分数失败：" + e.getMessage());
        }
    }

    private void exportTeacherScores(HttpServletResponse response) throws Exception {
        try {
            // 查询教师分数统计数据
            List<Map<String, Object>> scoreData = new ArrayList<>();
            List<com.evaluation.entity.TeacherEvaluatingRelation> relations = teacherEvaluatingRelationService.lambdaQuery()
                    .eq(com.evaluation.entity.TeacherEvaluatingRelation::getCpbs, "1")
                    .orderByDesc(com.evaluation.entity.TeacherEvaluatingRelation::getTotalscore)
                    .list();

            for (com.evaluation.entity.TeacherEvaluatingRelation relation : relations) {
                Map<String, Object> item = new HashMap<>();
                item.put("被测评教师", relation.getBcpjs());
                item.put("测评教师", relation.getCpjs());
                item.put("总分", relation.getTotalscore());
                item.put("第一分数", relation.getFirstscore());
                item.put("第二分数", relation.getTwoscore());
                item.put("第三分数", relation.getThreescore());
                item.put("第四分数", relation.getFourscore());
                item.put("测评时间", relation.getCpsj());
                scoreData.add(item);
            }

            String fileName = "教师分数统计_" + System.currentTimeMillis();
            com.evaluation.util.ExcelUtil.exportExcel(response, fileName, scoreData);
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("导出教师分数失败：" + e.getMessage());
        }
    }

    private void exportIndicators(HttpServletResponse response) throws Exception {
        try {
            List<com.evaluation.entity.Indicators> indicatorsList = indicatorsService.list();

            String[] headers = {"指标编号", "指标名称", "指标描述", "测评类型", "排序"};
            String[] fields = {"zbbh", "zbmc", "zbms", "cplx", "px"};
            String fileName = "考核指标_" + System.currentTimeMillis() + ".xlsx";

            com.evaluation.util.ExcelUtil.writeExcel(response, indicatorsList, headers, fields, fileName);
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("导出考核指标失败：" + e.getMessage());
        }
    }

    private void exportIndicatorPoints(HttpServletResponse response) throws Exception {
        try {
            List<com.evaluation.entity.IndicatorsPoints> pointsList = indicatorsPointsService.list();

            String[] headers = {"指标编号", "考核点编号", "考核点名称", "考核点详解", "A选项分数", "B选项分数", "C选项分数", "D选项分数", "E选项分数"};
            String[] fields = {"zbbh", "khdbh", "khdmc", "khdxj", "a", "b", "c", "d", "e"};
            String fileName = "考核点_" + System.currentTimeMillis() + ".xlsx";

            com.evaluation.util.ExcelUtil.writeExcel(response, pointsList, headers, fields, fileName);
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("导出考核点失败：" + e.getMessage());
        }
    }

    private void exportPositions(HttpServletResponse response) throws Exception {
        try {
            List<com.evaluation.entity.PositionType> positionList = positionTypeService.lambdaQuery()
                    .eq(com.evaluation.entity.PositionType::getGwzt, "0")
                    .orderByAsc(com.evaluation.entity.PositionType::getGwbh)
                    .list();

            String[] headers = {"岗位编号", "岗位名称", "岗位类型", "状态"};
            String[] fields = {"gwbh", "gwmc", "gwlx", "gwzt"};
            String fileName = "岗位信息_" + System.currentTimeMillis() + ".xlsx";

            com.evaluation.util.ExcelUtil.writeExcel(response, positionList, headers, fields, fileName);
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("导出岗位信息失败：" + e.getMessage());
        }
    }

    private void exportSummaryReport(HttpServletResponse response) throws Exception {
        try {
            List<Map<String, Object>> summaryData = new ArrayList<>();

            // 部门测评汇总
            List<com.evaluation.entity.DeptEvaluatingRelation> deptRelations = deptEvaluatingRelationService.lambdaQuery()
                    .eq(com.evaluation.entity.DeptEvaluatingRelation::getCpbs, "1")
                    .list();

            Map<String, Object> deptSummary = new HashMap<>();
            deptSummary.put("测评类型", "部门测评");
            deptSummary.put("总测评数", deptRelations.size());
            deptSummary.put("平均分", deptRelations.stream().mapToDouble(r -> r.getTotalscore() != null ? r.getTotalscore() : 0).average().orElse(0));
            deptSummary.put("最高分", deptRelations.stream().mapToDouble(r -> r.getTotalscore() != null ? r.getTotalscore() : 0).max().orElse(0));
            deptSummary.put("最低分", deptRelations.stream().mapToDouble(r -> r.getTotalscore() != null ? r.getTotalscore() : 0).min().orElse(0));
            summaryData.add(deptSummary);

            // 教师测评汇总
            List<com.evaluation.entity.TeacherEvaluatingRelation> teacherRelations = teacherEvaluatingRelationService.lambdaQuery()
                    .eq(com.evaluation.entity.TeacherEvaluatingRelation::getCpbs, "1")
                    .list();

            Map<String, Object> teacherSummary = new HashMap<>();
            teacherSummary.put("测评类型", "教师测评");
            teacherSummary.put("总测评数", teacherRelations.size());
            teacherSummary.put("平均分", teacherRelations.stream().mapToDouble(r -> r.getTotalscore() != null ? r.getTotalscore() : 0).average().orElse(0));
            teacherSummary.put("最高分", teacherRelations.stream().mapToDouble(r -> r.getTotalscore() != null ? r.getTotalscore() : 0).max().orElse(0));
            teacherSummary.put("最低分", teacherRelations.stream().mapToDouble(r -> r.getTotalscore() != null ? r.getTotalscore() : 0).min().orElse(0));
            summaryData.add(teacherSummary);

            String fileName = "测评汇总报表_" + System.currentTimeMillis();
            com.evaluation.util.ExcelUtil.exportExcel(response, fileName, summaryData);
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("导出测评汇总报表失败：" + e.getMessage());
        }
    }

    private void exportDetailReport(HttpServletResponse response) throws Exception {
        try {
            List<Map<String, Object>> detailData = new ArrayList<>();

            // 详细部门测评数据
            List<com.evaluation.entity.DeptEvaluatingRelation> deptRelations = deptEvaluatingRelationService.list();
            for (com.evaluation.entity.DeptEvaluatingRelation relation : deptRelations) {
                Map<String, Object> item = new HashMap<>();
                item.put("测评类型", "部门测评");
                item.put("测评编号", relation.getBh());
                item.put("被测评对象", relation.getBcpbm());
                item.put("测评教师", relation.getCpjs());
                item.put("测评指标", relation.getCpzbbh());
                item.put("测评状态", "1".equals(relation.getCpbs()) ? "已完成" : "未完成");
                item.put("总分", relation.getTotalscore());
                item.put("第一分数", relation.getFirstscore());
                item.put("第二分数", relation.getTwoscore());
                item.put("第三分数", relation.getThreescore());
                item.put("第四分数", relation.getFourscore());
                item.put("测评时间", relation.getCpsj());
                detailData.add(item);
            }

            // 详细教师测评数据
            List<com.evaluation.entity.TeacherEvaluatingRelation> teacherRelations = teacherEvaluatingRelationService.list();
            for (com.evaluation.entity.TeacherEvaluatingRelation relation : teacherRelations) {
                Map<String, Object> item = new HashMap<>();
                item.put("测评类型", "教师测评");
                item.put("测评编号", relation.getBh());
                item.put("被测评对象", relation.getBcpjs());
                item.put("测评教师", relation.getCpjs());
                item.put("测评指标", relation.getCpzbbh());
                item.put("测评状态", "1".equals(relation.getCpbs()) ? "已完成" : "未完成");
                item.put("总分", relation.getTotalscore());
                item.put("第一分数", relation.getFirstscore());
                item.put("第二分数", relation.getTwoscore());
                item.put("第三分数", relation.getThreescore());
                item.put("第四分数", relation.getFourscore());
                item.put("测评时间", relation.getCpsj());
                detailData.add(item);
            }

            String fileName = "详细测评报表_" + System.currentTimeMillis();
            com.evaluation.util.ExcelUtil.exportExcel(response, fileName, detailData);
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("导出详细测评报表失败：" + e.getMessage());
        }
    }

    private void exportStatisticsReport(HttpServletResponse response) throws Exception {
        try {
            List<Map<String, Object>> statisticsData = new ArrayList<>();

            // 基础统计信息
            Map<String, Object> basicStats = new HashMap<>();
            basicStats.put("统计项目", "基础数据");
            basicStats.put("部门总数", deptService.lambdaQuery().eq(com.evaluation.entity.Dept::getBmzt, "0").count());
            basicStats.put("教师总数", teacherService.lambdaQuery().eq(com.evaluation.entity.Teacher::getJszt, "0").count());
            basicStats.put("考核指标总数", indicatorsService.count());
            basicStats.put("岗位类型总数", positionTypeService.lambdaQuery().eq(com.evaluation.entity.PositionType::getGwzt, "0").count());
            statisticsData.add(basicStats);

            // 测评进度统计
            Map<String, Object> progressStats = new HashMap<>();
            progressStats.put("统计项目", "测评进度");
            long totalDeptEvaluations = deptEvaluatingRelationService.count();
            long completedDeptEvaluations = deptEvaluatingRelationService.lambdaQuery()
                    .eq(com.evaluation.entity.DeptEvaluatingRelation::getCpbs, "1").count();
            long totalTeacherEvaluations = teacherEvaluatingRelationService.count();
            long completedTeacherEvaluations = teacherEvaluatingRelationService.lambdaQuery()
                    .eq(com.evaluation.entity.TeacherEvaluatingRelation::getCpbs, "1").count();

            progressStats.put("部门测评总数", totalDeptEvaluations);
            progressStats.put("部门测评完成数", completedDeptEvaluations);
            progressStats.put("部门测评完成率", totalDeptEvaluations > 0 ?
                    String.format("%.2f%%", (double) completedDeptEvaluations / totalDeptEvaluations * 100) : "0%");
            progressStats.put("教师测评总数", totalTeacherEvaluations);
            progressStats.put("教师测评完成数", completedTeacherEvaluations);
            progressStats.put("教师测评完成率", totalTeacherEvaluations > 0 ?
                    String.format("%.2f%%", (double) completedTeacherEvaluations / totalTeacherEvaluations * 100) : "0%");
            statisticsData.add(progressStats);

            String fileName = "统计分析报表_" + System.currentTimeMillis();
            com.evaluation.util.ExcelUtil.exportExcel(response, fileName, statisticsData);
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("导出统计分析报表失败：" + e.getMessage());
        }
    }

    /**
     * 导出部门指标分数
     */
    private void exportDeptIndicatorScores(HttpServletResponse response) throws Exception {
        List<com.evaluation.entity.DeptIndicatorsScore> list = deptIndicatorsScoreService.list(
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.evaluation.entity.DeptIndicatorsScore>().orderByDesc("BH"));
        List<Map<String, Object>> exportData = new ArrayList<>();

        for (com.evaluation.entity.DeptIndicatorsScore score : list) {
            // 使用LinkedHashMap保证字段顺序
            Map<String, Object> map = new java.util.LinkedHashMap<>();
            
            // 1. 部门编号
            map.put("部门编号", score.getBcpbm() != null ? score.getBcpbm() : "");
            
            // 2. 部门名称
            com.evaluation.entity.Dept dept = deptService.getOne(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.evaluation.entity.Dept>().eq("BMBH", score.getBcpbm()));
            if (dept != null) {
                map.put("部门名称", dept.getBmmc() != null ? dept.getBmmc() : "");
            } else {
                // 如果按部门编号找不到，尝试按部门名称查找
                dept = deptService.getOne(
                    new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.evaluation.entity.Dept>().eq("BMMC", score.getBcpbm()));
                map.put("部门名称", dept != null && dept.getBmmc() != null ? dept.getBmmc() : (score.getBcpbm() != null ? score.getBcpbm() : ""));
            }
            
            // 3. 指标编号
            map.put("指标编号", score.getCpzbbh() != null ? score.getCpzbbh() : "");
            
            // 4. 测评权重编号
            map.put("测评权重编号", score.getCpqzbh() != null ? score.getCpqzbh() : "");
            
            // 5. 测评权重名称
            com.evaluation.entity.IndicatorsWf indicatorsWf = null;
            if (score.getCpqzbh() != null && !score.getCpqzbh().trim().isEmpty()) {
                indicatorsWf = indicatorsWfService.getOne(
                    new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.evaluation.entity.IndicatorsWf>().eq("QZBH", score.getCpqzbh()));
            }
            if (indicatorsWf != null && indicatorsWf.getQzmc() != null) {
                map.put("测评权重名称", indicatorsWf.getQzmc());
            } else {
                map.put("测评权重名称", "");
            }
            
            // 6. 测评指标权重
            map.put("测评指标权重", score.getCpzbqz() != null ? score.getCpzbqz() : "");
            
            // 7. 分数
            map.put("分数", score.getScore() != null ? score.getScore() : "");

            exportData.add(map);
        }

        if (!exportData.isEmpty()) {
            String fileName = "部门指标分数_" + System.currentTimeMillis();
            com.evaluation.util.ExcelUtil.exportExcel(response, fileName, exportData);
        }
    }

    /**
     * 导出部门总分
     */
    private void exportDeptTotalScores(HttpServletResponse response) throws Exception {
        List<com.evaluation.entity.DeptScore> list = deptScoreService.list(
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.evaluation.entity.DeptScore>().orderByDesc("SCORE"));
        List<Map<String, Object>> exportData = new ArrayList<>();

        for (com.evaluation.entity.DeptScore score : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("编号", score.getBh());
            map.put("部门编号", score.getBcpbm());
            map.put("总分", score.getScore());

            // 获取部门信息
            com.evaluation.entity.Dept dept = deptService.getOne(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.evaluation.entity.Dept>().eq("BMBH", score.getBcpbm()));
            if (dept != null) {
                map.put("部门名称", dept.getBmmc());
            } else {
                // 如果按部门编号找不到，尝试按部门名称查找
                dept = deptService.getOne(
                    new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.evaluation.entity.Dept>().eq("BMMC", score.getBcpbm()));
                map.put("部门名称", dept != null ? dept.getBmmc() : score.getBcpbm());
            }

            exportData.add(map);
        }

        if (!exportData.isEmpty()) {
            String fileName = "部门总分_" + System.currentTimeMillis();
            com.evaluation.util.ExcelUtil.exportExcel(response, fileName, exportData);
        }
    }

    /**
     * 导出教师指标分数
     */
    private void exportTeacherIndicatorScores(HttpServletResponse response) throws Exception {
        List<com.evaluation.entity.TeacherIndicatorsScore> list = teacherIndicatorsScoreService.list(
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.evaluation.entity.TeacherIndicatorsScore>().orderByDesc("BH"));
        List<Map<String, Object>> exportData = new ArrayList<>();

        for (com.evaluation.entity.TeacherIndicatorsScore score : list) {
            Map<String, Object> map = new LinkedHashMap<>();
            
            // 获取教师信息 - 先尝试按教师编号查找，再尝试按教师姓名查找
            com.evaluation.entity.Teacher teacher = teacherService.getOne(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.evaluation.entity.Teacher>().eq("JSBH", score.getBcpjs()));
            if (teacher == null) {
                // 如果按编号找不到，尝试按姓名查找
                teacher = teacherService.getOne(
                    new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.evaluation.entity.Teacher>().eq("JSXM", score.getBcpjs()));
            }
            if (teacher == null) {
                // 如果按姓名也找不到，尝试按工号查找
                teacher = teacherService.getOne(
                    new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.evaluation.entity.Teacher>().eq("JSGH", score.getBcpjs()));
            }
            
            // 按照要求的顺序和字段导出数据
            // 1. 教师编号
            if (teacher != null && teacher.getJsbh() != null) {
                map.put("教师编号", String.valueOf(teacher.getJsbh()));
            } else {
                map.put("教师编号", score.getBcpjs() != null ? score.getBcpjs() : "");
            }
            
            // 2. 教师工号
            if (teacher != null && teacher.getJsgh() != null) {
                map.put("教师工号", teacher.getJsgh());
            } else {
                map.put("教师工号", "");
            }
            
            // 3. 教师姓名
            if (teacher != null && teacher.getJsxm() != null) {
                map.put("教师姓名", teacher.getJsxm());
            } else {
                map.put("教师姓名", score.getBcpjs() != null ? score.getBcpjs() : "");
            }
            
            // 4. 指标编号
            map.put("指标编号", score.getCpzbbh() != null ? score.getCpzbbh() : "");
            
            // 5. 测评权重编号
            map.put("测评权重编号", score.getCpqzbh() != null ? score.getCpqzbh() : "");
            
            // 获取测评权重信息
            com.evaluation.entity.IndicatorsWf indicatorsWf = null;
            if (score.getCpqzbh() != null && !score.getCpqzbh().trim().isEmpty()) {
                indicatorsWf = indicatorsWfService.getOne(
                    new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.evaluation.entity.IndicatorsWf>().eq("QZBH", score.getCpqzbh()));
            }
            
            // 6. 测评权重名称
            if (indicatorsWf != null && indicatorsWf.getQzmc() != null) {
                map.put("测评权重名称", indicatorsWf.getQzmc());
            } else {
                map.put("测评权重名称", "");
            }
            
            // 7. 测评指标权重
            if (score.getCpzbqz() != null) {
                map.put("测评指标权重", score.getCpzbqz());
            } else {
                map.put("测评指标权重", "");
            }
            
            // 8. 分数
            if (score.getScore() != null) {
                map.put("分数", score.getScore());
            } else {
                map.put("分数", "");
            }

            exportData.add(map);
        }

        if (!exportData.isEmpty()) {
            // 指定表头顺序，确保导出Excel的列顺序正确
            List<String> headers = new ArrayList<>();
            headers.add("教师编号");
            headers.add("教师工号");
            headers.add("教师姓名");
            headers.add("指标编号");
            headers.add("测评权重编号");
            headers.add("测评权重名称");
            headers.add("测评指标权重");
            headers.add("分数");
            com.evaluation.util.ExcelUtil.exportExcel(response, "教师指标分数", exportData, headers);
        }
    }

    /**
     * 导出教师总分
     */
    private void exportTeacherTotalScores(HttpServletResponse response) throws Exception {
        List<com.evaluation.entity.TeacherScore> list = teacherScoreService.list(
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.evaluation.entity.TeacherScore>().orderByDesc("SCORE"));
        List<Map<String, Object>> exportData = new ArrayList<>();

        for (com.evaluation.entity.TeacherScore score : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("编号", score.getBh());
            map.put("教师编号", score.getBcpjs());
            map.put("总分", score.getScore());

            // 获取教师信息 - 先尝试按教师编号查找，再尝试按教师姓名查找
            com.evaluation.entity.Teacher teacher = teacherService.getOne(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.evaluation.entity.Teacher>().eq("JSBH", score.getBcpjs()));
            if (teacher == null) {
                // 如果按编号找不到，尝试按姓名查找
                teacher = teacherService.getOne(
                    new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.evaluation.entity.Teacher>().eq("JSXM", score.getBcpjs()));
            }
            if (teacher == null) {
                // 如果按姓名也找不到，尝试按工号查找
                teacher = teacherService.getOne(
                    new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.evaluation.entity.Teacher>().eq("JSGH", score.getBcpjs()));
            }

            if (teacher != null) {
                map.put("教师姓名", teacher.getJsxm());
                map.put("部门编号", teacher.getBmbh());

                // 获取部门名称
                com.evaluation.entity.Dept dept = deptService.getOne(
                    new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.evaluation.entity.Dept>().eq("BMBH", teacher.getBmbh()));
                map.put("部门名称", dept != null ? dept.getBmmc() : "");
            } else {
                map.put("教师姓名", score.getBcpjs());
                map.put("部门编号", "");
                map.put("部门名称", "");
            }

            exportData.add(map);
        }

        if (!exportData.isEmpty()) {
            String fileName = "教师总分_" + System.currentTimeMillis();
            com.evaluation.util.ExcelUtil.exportExcel(response, fileName, exportData);
        }
    }
}
